/*
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * IPList
 * Idea and C# code by Bo Norgaard
 * C++ code by SSA
 *
 */

#ifndef IPLIST_H
#define IPLIST_H

#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>

class IPList 
{

private:
	class IPArrayList 
	{
	private:
		bool isSorted;
        std::vector< UINT32 > ipNumList;
        UINT32 ipmask;

	public:
		IPArrayList (UINT32 mask) 
			:ipmask(mask)
			,isSorted(false)
		{
        }

		void Add(UINT32 IPNum) {
            isSorted = false;
            ipNumList.push_back(IPNum & ipmask);
        }

        bool Check(UINT32 IPNum) {
            bool found = false;
            if (ipNumList.size()>0) {
                if (!isSorted) {
                    std::sort(ipNumList.begin(), ipNumList.end() ); //, compareMyDataPredicate;
                    isSorted=true;
                }
                IPNum = IPNum & ipmask;
                // if (ipNumList.BinarySearch(IPNum)>=0) found=true;
				if (std::find(ipNumList.begin(), ipNumList.end(), IPNum) != ipNumList.end()) found = true;
            }
            return found;
        }

		void Clear() {
            ipNumList.clear();
            isSorted = false;
        }

		UINT32 getMask() {return ipmask;}
	};

private:
        std::vector< boost::shared_ptr<IPArrayList> > ipRangeList;
		std::map<UINT32, UINT32> maskList;
        std::vector< UINT32 > usedList;

public:
		IPList();
		~IPList();
        UINT32 parseIP(const std::string& IPNumber);
		void Add(const std::string& IPNumber);
		void Add(UINT32 ip);

		void Add(const std::string& IPNumber, const std::string& Mask);
		void Add(UINT32 ip, UINT32 umask);
        void Add(const std::string& IPNumber, UINT32 maskLevel);

		void AddRange(UINT32 fromIP, UINT32 toIP);
		void AddRange(const std::string& fromIP, const std::string& toIP);

		bool CheckNumber(UINT32 ip);
        bool CheckNumber(const std::string& ipNumber);

		void Clear();

private:
		UINT32 getMaskByLevel(UINT32 maskLevel);
};

#endif // IPLIST_H
